﻿// //------------------------------------------------------------------------------
// // <copyright file="" company="Dascoba Development">
// //  Copyright © Dascoba Development 2010
// // </copyright>
// //------------------------------------------------------------------------------
namespace Dascoba.Umb.FileManager.Support
{
    using System;
    using System.IO;
    using System.Linq;
    using System.Web;
    using System.Web.UI;

    using Dascoba.Umb.FileManager.Config;

    using umbraco;
    using umbraco.BusinessLogic.Actions;
    using umbraco.uicontrols;

    /// <summary>
    ///   Common Utilities
    /// </summary>
    public static class Util
    {
        /// <summary>
        ///   Maps the URL from the location application path.
        /// </summary>
        /// <param name = "path">The path.</param>
        /// <returns>The map url.</returns>
        internal static string MapUrl(string path)
        {
            string url;
            try
            {
                var root = Constants.ApplicationRootUrl;

                if (root == null)
                {
                    return "/";
                }

                url = String.Format("/{0}", path.Replace(root, String.Empty).Replace(@"\", "/"));
            }
            catch
            {
                url = "/";
            }

            return url.Replace("//", "/");
        }

        /// <summary>
        ///   Maps the path.
        /// </summary>
        /// <param name = "url">The URL.</param>
        /// <returns>The map path.</returns>
        internal static string MapPath(string url)
        {
            return HttpContext.Current.Server.MapPath(url);
        }

        /// <summary>
        ///   Finds a Control recursively.  (Finds the first match that exists)
        /// </summary>
        /// <param name = "rootControl">The root control element.</param>
        /// <param name = "controlToFindId">ID of the control to find.</param>
        /// <returns>Found Control</returns>
        internal static Control FindControlRecursive(Control rootControl, string controlToFindId)
        {
            if (rootControl == null)
            {
                return rootControl;
            }

            return rootControl.ID == controlToFindId
                       ? rootControl
                       : (from Control control in rootControl.Controls
                          select FindControlRecursive(control, controlToFindId)).FirstOrDefault(
                              foundCtl => foundCtl != null);
        }

        /// <summary>
        ///   Cleans the string by removing line break characters, removing white-space from the ends
        ///   and changing all uppercase letters to lower.
        /// </summary>
        /// <param name = "value">The value.</param>
        /// <returns>Clean String</returns>
        internal static string CleanLowerString(string value)
        {
            return value.Replace("\r\n", String.Empty).Trim().ToLower();
        }

        /// <summary>
        /// Gets the javascript function.
        /// </summary>
        /// <param name="opener">The opener.</param>
        /// <returns></returns>
        internal static string GetJsFunction(FileOpener opener)
        {
            var goodFunctionName = GetGoodFunctionName(opener.Function);
            string fullFunction;

            if (opener.OpenModal)
            {
                fullFunction =
                    string.Format(
                        @"
                function {0}(file) {{
                    parent.openModal('{1}/Pages/{2}?isModal=true&file=' + file, '{3} - {4}', 600, 810);}}
                ",
                        goodFunctionName,
                        Constants.FileManagerGlobalUrl,
                        opener.Page,
                        opener.Name,
                        opener.FileType);
            }
            else
            {
                fullFunction =
                    string.Format(
                        @"
                function {0}(file) {{
                    parent.right.document.location.href = '{1}/Pages/{2}?isModal=false&file=' + file;}}
                ",
                        goodFunctionName,
                        Constants.FileManagerGlobalUrl,
                        opener.Page);
            }
            return fullFunction;
        }

        /// <summary>
        ///   Gets the name of the function without spaces.
        /// </summary>
        /// <param name = "functionName">The name.</param>
        /// <returns></returns>
        internal static string GetGoodFunctionName(string functionName)
        {
            return functionName.Replace(" ", "");
        }

        /// <summary>
        ///   Gets the file size text.
        /// </summary>
        /// <param name = "sizeInBytes">The size in bytes.</param>
        /// <returns></returns>
        internal static string GetFileSizeText(long sizeInBytes)
        {
            var sizeText = sizeInBytes + " Bytes";

            if (sizeInBytes > 1024 && sizeInBytes < 1048576)
            {
                sizeText = (sizeInBytes / 1024) + " KB";
            }

            if (sizeInBytes > 1048576 && sizeInBytes < 1073741824)
            {
                sizeText = (sizeInBytes / 1024 / 1024) + " MB";
            }

            if (sizeInBytes > 1073741824 && sizeInBytes < 1099511627776)
            {
                sizeText = (sizeInBytes / 1024 / 1024) + " GB";
            }

            return sizeText;
        }

        /// <summary>
        ///   Gets the extension without the dot
        /// </summary>
        /// <param name = "fileName">Name of the file.</param>
        /// <returns></returns>
        internal static string GetSimpleExtension(string fileName)
        {
            return Path.GetExtension(fileName).Replace(".", "");
        }

        /// <summary>
        ///   Shortened the string.
        /// </summary>
        /// <param name = "value">The value.</param>
        /// <param name = "maxChars">The max chars.</param>
        /// <returns></returns>
        internal static string ShortenedString(string value, int maxChars)
        {
            if (value.Length > maxChars)
            {
                return value.Substring(0, maxChars) + "...";
            }

            return value;
        }

        /// <summary>
        ///   Converts the actions to toolbar.
        /// </summary>
        /// <param name = "menu">The menu.</param>
        /// <returns></returns>
        internal static ScrollingMenu GetScrollingMenuFromContextMenu(ContextMenu menu)
        {
            var toolBar = new ScrollingMenu();
            foreach (var action in menu)
            {
                if (action.GetType() == typeof(ContextMenuSeperator))
                {
                    toolBar.InsertSplitter();
                }
                else
                {
                    var button = toolBar.NewImageButton();
                    button.ImageURL = string.Format("{0}/{1}", GlobalSettings.Path, action.Icon);
                    button.ToolTip = ui.Text("actions", action.Alias);
                    button.OnClickCommand = action.JsFunctionName;
                }
            }
            return toolBar;
        }

        public static bool SupportsJQueryTree
        {
            get
            {
                return !GlobalSettings.CurrentVersion.StartsWith("4.0");
            }
        }
    }
}